package com.sd365.permission.centre.service.impl;

/**
 * @ClassName UserServiceImpl
 * @Author 史旭升
 * @Date 2022/12/26 9:29
 * @Version 1.0
 **/

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.sd365.common.core.annotation.stuffer.IdGenerator;
import com.sd365.common.core.common.aop.MyPageInfo;
import com.sd365.common.core.common.constant.EntityConsts;
import com.sd365.common.core.common.exception.BusinessException;
import com.sd365.common.core.context.BaseContextHolder;
import com.sd365.common.util.BeanUtil;
import com.sd365.permission.centre.dao.mapper.*;
import com.sd365.permission.centre.entity.*;
import com.sd365.permission.centre.pojo.dto.RoleDTO;
import com.sd365.permission.centre.pojo.dto.UserDTO;
import com.sd365.permission.centre.pojo.query.UserQuery;
import com.sd365.permission.centre.service.UserService;
import com.sd365.permission.centre.service.exception.UserCentreExceptionCode;
import com.sd365.permission.centre.service.util.DefaultTenant;
import com.sd365.permission.centre.service.util.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class UserServiceImpl extends AbstractBaseDataServiceImpl implements UserService {

    public static final String NOTEULL_ID = "id不能为空";

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    DefaultTenant defaultTenant;



    @Override
    public Boolean add(UserDTO userDTO) {
        //userDTO不能为空
        if (userDTO ==null) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATAM_SERVICE_OTHER_EXCEPTION_CODE, new Exception("userDTO不为空"));
        }
        //code不能重复
        //根据code查询是否重复，
        User currentUser = userMapper.selectByCode(userDTO.getCode());
        //判断是否存在
        if(currentUser!=null){
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATAM_SERVICE_OTHER_EXCEPTION_CODE, new Exception("工号不能重複"));
        }else {
            User user = BeanUtil.copy(userDTO, User.class);
            // 数据填充
            user.setId(idGenerator.snowflakeId());
            super.baseDataStuff4Add(user);
            super.baseDataStuffCommonPros(user);
            user.setVersion(EntityConsts.INITIAL_VERSION);
            //密码加密
            user.setPassword(Md5Utils.digestHex(user.getPassword()));
            //插入数据到user表（主表）
            userMapper.insert(user);
            UserRole userRole = new UserRole();
            //获取角色列表
            List<RoleDTO> roleList = userDTO.getRoleList();
            //逐条添加
            for (RoleDTO roleDTO : roleList) {
                userRole.setUserId(user.getId());
                userRole.setRoleId(roleDTO.getId());
                //数据填充
                userRole.setId(idGenerator.snowflakeId());
                super.baseDataStuff4Add(userRole);
                super.baseDataStuffCommonPros(userRole);
                //版本为1
                userRole.setVersion(INITIALIZE_VERSION_VALUE);
                //插入到从表
                userRoleMapper.insert(userRole);
            }
            return true;
        }
    }


    @Override
    public Boolean remove(Long id, Long version) {
        //id不能为空且user必须存在
        User user = userMapper.selectById(id);
        if(id ==null||user==null){
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATAM_SERVICE_OTHER_EXCEPTION_CODE, new Exception("参数异常"));
        }
        //先删从表再删主表
            Boolean tag = false;
            //自动拆箱获取int结果(根据id删除从表user_Role)
            if(userRoleMapper.deleteAllByUserID(id) > 0){
                //根据id删除主表user
                Example example = new Example(User.class);
                example.createCriteria().andEqualTo("id", id);
                 tag = userMapper.deleteByExample(example) > 0;
            }
            return tag;
    }

    /**
     *修改用户
     * @author shi xusheng
     * @date 2022/12/27 11:45
     * @param userDTO
     * @return java.lang.Boolean
     */
    @Override
    public Boolean modify(UserDTO userDTO) {
        //userDTO不为空，id字段不为空
        if (null == userDTO||userDTO.getId()==null) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATAM_SERVICE_OTHER_EXCEPTION_CODE, new Exception("参数异常"));
        }
        boolean flag = false;
        //通过id查找用户
        User currentUser = userMapper.selectById(userDTO.getId());
        //修改当前对象，工号可重复，修改其他对象工号不可以重复(currentUser不为空且要修改的对象不是当前选中对象)
        if(currentUser != null && !userDTO.getCode().equals(currentUser.getCode())){
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATAM_SERVICE_OTHER_EXCEPTION_CODE, new Exception("参数异常"));
        }else {
            User user = BeanUtil.copy(userDTO, User.class);
            //更新用户
            userMapper.updateByPrimaryKeySelective(user);
            //角色集合不为空，接下来对用户拥有角色集合进行更新
            if (userDTO.getRoleList() != null && !userDTO.getRoleList().isEmpty()) {
                //获取角色集合，先删除在更新
                List<RoleDTO> roleList = userDTO.getRoleList();
                userRoleMapper.deleteAllByUserID(userDTO.getId());
                for (RoleDTO role : roleList) {
                    //逐个数据更新
                    UserRole userRole = new UserRole();
                    userRole.setUserId(user.getId());
                    userRole.setRoleId(role.getId());
                    //数据填充
                    userRole.setId(idGenerator.snowflakeId());
                    super.baseDataStuff4Add(userRole);
                    super.baseDataStuffCommonPros(userRole);
                    //版本设为1
                    userRole.setVersion(INITIALIZE_VERSION_VALUE);
                    //更新
                    int num = userRoleMapper.insert(userRole);
                    if(num > 0){
                        flag = true;
                    }
                }
            }
        }
        return flag;
    }

    /**
     *修改用户角色(分配角色,覆盖原有角色)
     * @author shi xusheng
     * @date 2022/12/28 12:36
     * @param userDTOS
     * @return java.lang.Boolean
     */
    @Override
    public Boolean modifyWithNewRole(UserDTO[] userDTOS) {
        boolean flag = false;
        for (UserDTO userDTO : userDTOS) {
            //逐个删除原有角色，
            userRoleMapper.deleteAllByUserID(userDTO.getId());
            List<RoleDTO> roleList = userDTO.getRoleList();
            //根据测试用例，roleList，不能为null，用户至少一个角色，一个都不选择抛异常
            for (RoleDTO roleDTO : roleList) {
                //逐个数据更新
                UserRole userRole = new UserRole();
                userRole.setUserId(userDTO.getId());
                userRole.setRoleId(roleDTO.getId());
                //数据填充
                userRole.setId(idGenerator.snowflakeId());
                super.baseDataStuff4Add(userRole);
                super.baseDataStuffCommonPros(userRole);
                //版本设为1
                userRole.setVersion(INITIALIZE_VERSION_VALUE);
                //更新
                if ( userRoleMapper.insert(userRole) > 0) {
                    flag = true;
                }
            }

        }
        return flag;
    }

    /**
     *查询用户
     * @author shi xusheng
     * @date 2022/12/30 2:37
     * @param userQuery
     * @return java.util.List<com.sd365.permission.centre.entity.User>
     */
    @Override
    public List<User> commonQuery(UserQuery userQuery) {
        //查询非空
        if (null == userQuery) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATAM_SERVICE_OTHER_EXCEPTION_CODE, new Exception("userQuery不能为空"));
        }
            //存储前端（userQuery）传来的参数
            User user = new User();
            user.setName(userQuery.getName());
            user.setCode(userQuery.getCode());
            user.setTel(userQuery.getTel());
            //查询的用户(分配了角色)，参数包含RoleId，通过角色查询
            if (userQuery.getRoleId() != null) {
                //根据role_id从basic_user_role表中查询到分配到该角色下的所有用户
                List<User> users = userMapper.commonByQueryRoleId(user, userQuery.getRoleId());
                for (User nUser : users) {
                    //角色所有的用户集合（user表）
                    nUser.setRoleList(roleMapper.selectRoleByUserid(nUser.getId()));
                    //md5加密密码
                    nUser.setPassword(Md5Utils.digestHex(nUser.getPassword()));
                }
                //分页参数设置
                Page<User> page = (Page) users;
                BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
                return users;
            } else {
                //查询的用户(没有分配)，通过查询到用户集合（basic_user_role表）
                List<User> userList = userMapper.commonQuery(user);
                //（user表）从该表查找到对应数据
                for (User currentUser : userList) {
                    currentUser.setRoleList(roleMapper.selectRoleByUserid(currentUser.getId()));
                    currentUser.setPassword(Md5Utils.digestHex(currentUser.getPassword()));
                }
                Page<User> page = (Page) userList;
                BaseContextHolder.set("pageInfo", JSON.toJSONString(new MyPageInfo(page.getTotal(), page.getPages())));
                return userList;
            }
    }

    /**
     *查询用户通过id，复制时查询对应数据回显
     * @author shi xusheng
     * @date 2022/12/30 22:38
     * @param id
     * @return com.sd365.permission.centre.pojo.vo.UserVO
     */
    @Override
    public User queryById(Long id) {
        if (null == id) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATAM_SERVICE_OTHER_EXCEPTION_CODE, new Exception(NOTEULL_ID));
        }
        //查询ID对应的用户
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATA_USER_DB_EXCEPTION_CODE, new Exception("没有查到数据！"));
        }
        //查询该用户的角色列表
        List<Role> roles = roleMapper.selectRoleByUserid(id);
        user.setRoleList(roles);
        return user;
    }

    /**
     *查询所有角色
     * @author shi xusheng
     * @date 2022/12/28 21:39
     * @return java.util.List<com.sd365.permission.centre.entity.Role>
     */
    @Override
    public List<Role> queryAllRole() {
        return roleMapper.selectAll();
    }

    /**
     *查询所有部门
     * @author shi xusheng
     * @date 2022/12/28 22:39
     * @return java.util.List<com.sd365.permission.centre.entity.Department>
     */
    @Override
    public List<Department> queryAllDepartment() {
        return departmentMapper.selectAll();
    }

    /**
     *查询所有职业
     * @author shi xusheng
     * @date 2022/12/29 22:40
     * @return java.util.List<com.sd365.permission.centre.entity.Position>
     */
    @Override
    public List<Position> queryAllPosition() {
        return positionMapper.selectAll();
    }

    /**
     *批量修改用户（(启停控制)）
     * @author shi xusheng
     * @date 2022/12/29 10:41
     * @param userDTOS
     * @return java.lang.Boolean
     */
    @Override
    public Boolean batchUpdate(UserDTO[] userDTOS) {
        boolean flag = false;
        //遍历
        for (UserDTO userDTO : userDTOS) {
            User user = BeanUtil.copy(userDTO, User.class);
            //逐个更新（更新状态，版本+1）
            if(userMapper.updateStatus(user)> 0){
                flag = true;
            }
        }
        return flag;
    }

    /**
     *批量删除
     * @author shi xusheng
     * @date 2022/12/28 15:42
     * @param userDTOS
     * @return java.lang.Boolean
     */
    @Override
    public Boolean batchDelete(UserDTO[] userDTOS) {
        Boolean tag = false;
        //遍历userDTOS逐个删除
        for (UserDTO userDTO : userDTOS) {
            //测试用例：检查字段id不能空
            if (userDTO.getId()==null) {
                throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATAM_SERVICE_OTHER_EXCEPTION_CODE, new Exception(NOTEULL_ID));
            }
            //先删从表再删主表
                //自动拆箱获取int结果(根据id删除从表user_Role中的数据)
                if(userRoleMapper.deleteAllByUserID(userDTO.getId()) > 0){
                    //根据id删除主表user中的数据
                    Example example = new Example(User.class);
                    example.createCriteria().andEqualTo("id", userDTO.getId());
                    tag = userMapper.deleteByExample(example) > 0;
                }
        }
        return tag;
    }

    /**
     * md5,没有用到该接口，使用的是工具类
     * @return boolean
     */
    @Override
    public Boolean firstStartMd5() {
        return true;
    }

    /**
     *重新更新密码，本次培训项目不需要实现这个
     * @author shi xusheng
     * @date 2022/12/27 15:45
     * @param userDTO
     * @return java.lang.Boolean
     */
    @Override
    public Boolean updatePassword(UserDTO userDTO) {
        return true;
    }

    /**
     *找回密码
     * @author shi xusheng
     * @date 2022/12/30 22:49
     * @param code
     * @return com.sd365.permission.centre.entity.User
     */
    @Override
    public User getUser(String code) {
        if (code!= null && !code.equals("")){
            throw new BusinessException(UserCentreExceptionCode.BUSINESS_BASEDATAM_SERVICE_OTHER_EXCEPTION_CODE, new Exception("code不能为空"));
        }
        User user = new User();
        if (code!=null&&!code.equals("")) {
            //通过code查找密码
            Example example = new Example(User.class);
            example.createCriteria().andEqualTo("code", code);
            user = userMapper.selectOneByExample(example);
        }
        return user;
    }
}
